package com.cnlxu.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.view.Window;
import android.widget.Toast;

import com.cnlxu.data.StickerView;
import com.cnlxu.database.DBManager;
import com.cnlxu.database.WordInfo;
import com.cnlxu.network.HttpProxy;
import com.example.cninlaxu.curltest.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    public TextView et;
    public TextView tv;
    private int screenWidth;
    private int screenHeight;
    private int lastX;
    private int lastY;
    private int left;
    private int top;
    private int right;
    private int bottom;
    private String queryString;
    private String TAG = "DICT";
    private StickerView stickerView = null;
    private StickerView stickerView1 = null;
    private List<Map<String, String>> listData = null;
    private SimpleAdapter adapter = null;

    private Handler mProgressHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            if(msg.what==1) {
              /*  tv.setText(msg.getData().getString("result"));
                Toast.makeText(MainActivity.this, msg.getData().getString("result"), Toast.LENGTH_SHORT).show();*/
                showResult(queryString, msg.getData().getString("result"));
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onStart(){
        super.onStart();
        Log.i(TAG,"onStart");
    }
    @Override
    protected void onRestart(){
        super.onRestart();
        Log.i(TAG,"onRestart");
    }
    @Override
    protected void onResume(){
        super.onResume();
        Log.i(TAG, "onResume");
    }

    @Override
    protected void onPause(){
        super.onPause();
        Log.i(TAG, "onPause");
    }
    @Override
    protected void onStop(){
        super.onStop();
        Log.i(TAG, "onStop");
    }
    @Override
    protected void onSaveInstanceState(Bundle outState){
        outState.putInt("lastX", lastX);
        outState.putInt("lastY", lastY);
        Log.i(TAG, "onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onRestoreInstanceState(Bundle saveInstance){
        lastX = saveInstance.getInt("lastX");
        lastY = saveInstance.getInt("lastY");
        Log.i(TAG, "onRestoreInstance");
        super.onRestoreInstanceState(saveInstance);
    }
    private void setListData(){
        listData = new ArrayList<Map<String,String>>();

        Map<String,String> map = new HashMap<String, String>();
        map.put("text", "分享");
        listData.add(map);

        map = new HashMap<String, String>();
        map.put("text", "检查新版本");
        listData.add(map);

        map = new HashMap<String, String>();
        map.put("text", "反馈意见");
        listData.add(map);

        map = new HashMap<String, String>();
        map.put("text", "关于我们");
        listData.add(map);
    }
    private DBManager dbManager = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //
        dbManager = new DBManager(this);
        // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);
        et = (EditText)findViewById(R.id.et_input);
        stickerView = (StickerView)findViewById(R.id.setting_list);
        stickerView1 = (StickerView)findViewById(R.id.setting_list_1);
        setListData();
        adapter = new SimpleAdapter(getApplicationContext(), listData, R.layout.cornerlist_item,
                new String[]{"text"}, new int[]{R.id.tv_test_count});
        stickerView.setAdapter(adapter);
        stickerView1.setAdapter(adapter);

        StickerView stickerView2 = (StickerView)findViewById(R.id.setting_list2);

        stickerView2.setAdapter(adapter);
        StickerView stickerView3 = (StickerView)findViewById(R.id.setting_list3);
        stickerView3.setAdapter(adapter);
        stickerView2.setOnTouchListener(new View.OnTouchListener(){
            @Override
        public boolean onTouch(View v, MotionEvent event){
                return dragView(v, event);
            }
        });
        ////////////////////////////
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels - 50;
       /* et.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return dragView(v,event);
            }
        });*/

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onQuery();
            }
        });
    }


    private WordInfo getLocalWord(String word)
    {
        WordInfo info = dbManager.query(word);
        return info;
    }
    private void storeWord(String word, String tranlation,String details, String more)
    {
        dbManager.add(word, tranlation, details, more);
    }

    private void onQuery(){
        queryString = et.getText().toString();
        if(queryString.isEmpty()){
            return;
        }

        new Thread( new Runnable() {
            public void run() {
                Message msg=new Message();
                msg.what=1;
                Bundle b = new Bundle();
                //check it already exist
                WordInfo info =  getLocalWord(queryString);
                if(info._id != -1) {
                    b.putString("result", info.translation);
                }else {
                    HttpProxy p =new HttpProxy();
                    // network process
                    String result = p.translation(queryString);
                    b.putString("result", result);
                    storeWord(queryString, result, "", "");

                }

                msg.setData(b);
                mProgressHandler.sendMessage(msg);
            }
        }).start();
    }
    private void showResult(String word, String result){
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.trans_dlg, (ViewGroup) findViewById(R.id.llayout_dlg));
        TextView tv = (TextView)layout.findViewById(R.id.tv_trans_result);
        tv.setText(result);
        new AlertDialog.Builder(this).setTitle(word).setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this,"On ok click",Toast.LENGTH_LONG).show();
            }
        }).setNegativeButton("取消", null).show();
    }

    private boolean dragView(View v, MotionEvent event){

        int action=event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                lastX = (int)event.getRawX();
                lastY = (int)event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int dx =(int)event.getRawX() - lastX;
                int dy =(int)event.getRawY() - lastY;

                left = v.getLeft() + dx;
                top = v.getTop() + dy;
                right = v.getRight() + dx;
                bottom = v.getBottom() + dy;
                if(left < 0){
                    left = 0;
                    right = left + v.getWidth();
                }
                if(right > screenWidth){
                    right = screenWidth;
                    left = right - v.getWidth();
                }
                if(top < 0){
                    top = 0;
                    bottom = top + v.getHeight();
                }
                if(bottom > screenHeight){
                    bottom = screenHeight;
                    top = bottom - v.getHeight();
                }
                v.layout(left, top, right, bottom);
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                break;
            default:
                break;
        }
        return true;
    }

}
